import React, { memo, useState } from 'react'
import type { FC, ReactNode } from 'react'
import { DatePicker, ConfigProvider } from 'antd'
import type { DatePickerProps, GetProps } from 'antd'
import locale from 'antd/locale/zh_CN'
import 'dayjs/locale/zh-cn'

import dayjs from 'dayjs'
// import { v4 as uuidv4 } from 'uuid'

import { useMyDispatch } from '../../../store'
import { setEndTime } from '../../../store/modules/create'

import fetchData from '../../../request'
type RangePickerProps = GetProps<typeof DatePicker.RangePicker>

interface IProps {
  children?: ReactNode
  endTime?: string
  id?: string
}

const ListTimeSelect: FC<IProps> = ({ endTime, id }) => {
  const dispatch = useMyDispatch()

  const [Time, setTime] = useState(
    endTime && endTime !== '永久有效'
      ? dayjs(endTime, 'YYYY-MM-DD HH:mm:ss')
      : '永久有效'
  )
  const onOk = (
    value: DatePickerProps['value'] | RangePickerProps['value']
  ) => {
    console.log('onOk: ', value)
  }
  return (
    <ConfigProvider
      locale={locale}
      theme={{
        token: {
          colorPrimary: '#d0e750'
        }
      }}
    >
      <DatePicker
        showTime
        placeholder={endTime}
        value={
          Time === '永久有效' ? undefined : dayjs(Time, 'YYYY-MM-DD HH:mm:ss')
        }
        onChange={(value, dateString) => {
          if (dateString) {
            setTime(String(dateString))
            dispatch(setEndTime(dateString))
            fetchData('/update', { id, endTime: dateString }, 'POST')
          } else {
            setTime('永久有效')
            dispatch(setEndTime('永久有效'))
            fetchData('/update', { id, endTime: '永久有效' }, 'POST')
          }
        }}
        onOk={onOk}
      />
    </ConfigProvider>
  )
}

export default memo(ListTimeSelect)
